package com.xjtu.platform.security.avator;

import com.xjtu.platform.common.*;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;


/**
 * @创建人 MBY381
 * @创建时间 2022/6/29 17:00
 * @描述 暂无
 */


@RestController
@RequestMapping("/avatar")
public class AvatarAPI {

    @Resource
    private CommonService commonService;

    @Resource
    private AvatarService avatarService;

    @RequestMapping(value = "/{filename}",method = RequestMethod.GET)
    public void getAvatar(@PathVariable String filename, HttpServletResponse response) throws IOException {
        Constants.checkPath();
        System.out.print("filename!:");
        System.out.println(filename);

        try {
            boolean exists=new File(Constants.AVATAR_DIR+"/"+filename).exists();
            System.out.println("头像文件"+filename+" "+exists);
            if(exists){
                InputStream in = new FileInputStream(Constants.AVATAR_DIR+"/"+filename);
                OutputStream out = response.getOutputStream();
                avatar(in, out);
            }else {
                System.out.println("头像文件不存在");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    @RequestMapping(value = "/setavatar",method = RequestMethod.POST)
    public Result uploadAvatar(MultipartFile avatar, @RequestHeader("Token") String token) throws IOException {
        Constants.checkPath();
        InputStream in = avatar.getInputStream();

        String name = UUID.randomUUID().toString();
        String submittedFilename = avatar.getOriginalFilename();
        String suffix = submittedFilename.substring(submittedFilename.lastIndexOf("."));
        String filename = name+suffix;
//        filename = filename.replace('.','-');

        OutputStream out = new FileOutputStream(Constants.AVATAR_DIR+"/"+filename);

        avatar(in, out);

        CurrentUser currentUser = TokenUtils.getUserInfo(token,commonService);

        avatarService.setAvatar(currentUser,filename);

        return Result.success();

    }

    //头像流
    public static void avatar(InputStream in, OutputStream out) throws IOException {
        byte[] b = new byte[10240];
        int len = -1;

        while((len=in.read(b))!=-1){
            out.write(b,0,len);
        }
        out.flush();
        out.close();
        in.close();
    }
}
